package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.user.model.UserInfo;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.util.AreaInfo;
import com.atguigu.gmall.user.util.BaiDuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户表 业务实现类
 *
 * @author atguigu
 * @since 2023-06-20
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 登录
     * 1.获取认证信息中账户查询账号信息是否存在
     * 2.判断用户提交密码是否一致
     * 3.验证通过-生成UUID令牌
     * 4.将令牌作为Key  用户信息作为Value  存入Redis 设置Key过期时间24小时
     * 5.按照接口文档响应业务数据(包含令牌跟用户信息)
     *
     * @param loginVo 认证信息中的 参数名称:loginName 参数值:可能是账号,手机号,邮箱号
     * @param request
     * @return
     */
    @Override
    public Map<String, Object> login(UserInfo loginVo, HttpServletRequest request) {
        //1.获取认证信息中账户查询账号信息是否存在
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(loginVo.getLoginName()) && StringUtils.isNotBlank(loginVo.getPasswd())) {
            queryWrapper.eq(UserInfo::getLoginName, loginVo.getLoginName())
                    .or().eq(UserInfo::getEmail, loginVo.getLoginName())
                    .or().eq(UserInfo::getPhoneNum, loginVo.getLoginName());
            UserInfo userInfo = this.getOne(queryWrapper);
            if (userInfo == null) {
                throw new RuntimeException("账号错误!");
            }
            //2.判断用户提交密码是否一致
            //2.1 对提交明文密码进行md5加密
            String userLoginPwd = DigestUtils.md5DigestAsHex(loginVo.getPasswd().getBytes());
            //2.2 验证密码是否正确
            if (!userInfo.getPasswd().equals(userLoginPwd)) {
                throw new RuntimeException("密码错误!");
            }
            //3.验证通过-生成UUID令牌
            String token = UUID.randomUUID().toString().replaceAll("-", "");

            //4.将令牌作为Key  用户信息作为Value  存入Redis 设置Key过期时间24小时
            JSONObject redisValueMap = new JSONObject();
            redisValueMap.put("id", userInfo.getId());
            AreaInfo area = BaiDuService.getArea(IpUtil.getIpAddress(request));
            if (area != null) {
                redisValueMap.put("city", area.getCity());//异地登录给用户进行预警短信,引导进行再次登录
            }
            redisValueMap.put("mac", "666");   //设备唯一标识 有手机客户端提交
            String key = "user:" + token;
            redisTemplate.opsForValue().set(key, redisValueMap, 24, TimeUnit.HOURS);

            //5.按照接口文档响应业务数据(包含令牌跟用户信息)
            HashMap<String, Object> loginResult = new HashMap<>();
            loginResult.put("token", token);
            loginResult.put("nickName", userInfo.getNickName());
            return loginResult;
        }
        return null;
    }

    @Override
    public void logout(String token) {
        String key = "user:"+token;
        redisTemplate.delete(key);
    }

}
